package model

import (
	"errors"
	"fmt"
	"ordersystem/config"
	"ordersystem/database"
	"time"
)

type Device struct {
	Id          int32     `json:"id" xml:"id" form:"id" gorm:"primaryKey"`
	Name        string    `json:"name" xml:"name" form:"name"`
	Description string    `json:"description" xml:"description" form:"description"`
	Number      int32     `json:"number" xml:"number" form:"number"`
	LabId       int32     `json:"lab_id" xml:"lab_id" form:"lab_id"`
	Creator     int32     `json:"creator" xml:"creator" form:"creator"`
	CreateAt    time.Time `json:"create_at" xml:"create_at" form:"create_at" gorm:"autoCreateTime"`
	UpdateAt    time.Time `json:"update_at" xml:"update_at" form:"update_at" gorm:"autoUpdateTime"`
}

func (device *Device) QueryDevice() error {
	conn := database.GetMysqlConnection()

	conn.Model(device).First(device)
	return nil
}

func QueryDeviceNumber(lab_id int) (int64, error) {
	conn := database.GetMysqlConnection()

	var result int64
	conn.Table(config.TABLE_DEVICES).Where("lab_id = ?", lab_id).Count(&result)
	return result, nil
}

func QueryDevicesByLabId(labId int) (interface{}, error) {
	conn := database.GetMysqlConnection()

	var result []Device
	conn.Model(&Device{}).Where("lab_id = ?", labId).Scan(&result)
	return result, nil
}

func (device *Device) CreateDevice() error {
	conn := database.GetMysqlConnection()

	affectedRows := conn.Model(device).Create(device).Commit().RowsAffected
	if affectedRows == 0 {
		return errors.New(config.RESPONSE_DATABASE_OPERATION_ERROR)
	}
	return nil
}

func (device *Device) UpdateDevice() error {
	fmt.Println(*device)
	conn := database.GetMysqlConnection()
	// result := conn.ToSQL(func(gorm *gorm.DB) *gorm.DB {
	// 	return gorm.Model(device).Updates(map[string]interface{}{
	// 		"name":        device.Name,
	// 		"number":      device.Number,
	// 		"description": device.Description})
	// })
	// fmt.Println(result)

	conn.Model(device).Updates(map[string]interface{}{
		"name":        device.Name,
		"number":      device.Number,
		"description": device.Description})
	return nil
}

func (device *Device) DeleteDevice() error {
	conn := database.GetMysqlConnection()

	if conn.Model(device).Delete(device).Commit().RowsAffected == 0 {
		return errors.New(config.RESPONSE_DATABASE_OPERATION_ERROR)
	}
	return nil
}
